namespace Jsl.FxCop
{
    using Microsoft.FxCop.Sdk;

    /// <summary>
    /// Searches for and flags empty event handlers.
    /// </summary>
    public class RemoveEmptyEventHandlers : BaseIntrospectionRule
    {
        #region Constructors
        /// <summary>
        /// Initializes a new instance of the <see cref="RemoveEmptyEventHandlers"/> class.
        /// </summary>
        public RemoveEmptyEventHandlers()
            : base(typeof(RemoveEmptyEventHandlers).Name, "Jsl.FxCop.Rules", typeof(RemoveEmptyEventHandlers).Assembly)
        {
        }
        #endregion Constructors

        #region Public Methods
        /// <summary>
        /// Checks each instruction of the method.
        /// </summary>
        /// <param name="member">The member to check.</param>
        /// <returns>The problems found if any.</returns>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", Justification = "The parameters are already validated.")]
        public override ProblemCollection Check(Member member)
        {
            // Only process methods.
            Method method = member as Method;
            if (method == null)
            {
                return this.Problems;
            }

            foreach (var eventInformation in EventHelper.EventsUsedInMethod(method))
            {
                if (eventInformation.Handler != null)
                {
                    if (eventInformation.IsEventAdder)
                    {
                        if (InstructionHelper.IsEmptyMethod(eventInformation.Handler))
                        {
                            this.Problems.Add(new Problem(this.GetResolution(), eventInformation.EventAddOrRemoveCall.SourceContext));
                        }
                    }
                }
            }

            return this.Problems;
        }
        #endregion Public Methods
    }
}
